iT邦幫忙

2025 iThome 鐵人賽

DAY 12
0
Software Development

用leetcode系統化學習C語言系列 第 12

指標(pointer)與動態記憶體(malloc/calloc/realloc/free)攻略-4

  • 分享至 

  • xImage
  •  

指標與結構體(常見模式)
typedef struct {
int id;
char *name;
} Person;

Person *new_person(const char *name) {
Person *p = malloc(sizeof *p); // 分配 Person
if (!p) return NULL;
p->id = 0;
p->name = malloc(strlen(name) + 1); // 為 name 分配空間
if (!p->name) { free(p); return NULL; }
strcpy(p->name, name);
return p;
}

void free_person(Person *p) {
free(p->name);
free(p);
}

realloc 範例(動態成長陣列)
int *arr = malloc(init_n * sizeof arr);
/
用到某程度想擴充 */
int *tmp = realloc(arr, new_n * sizeof *arr);
if (tmp == NULL) {
// realloc 失敗:arr 仍指向原來的塊(不可直接丟掉)
// 必須保留 arr,或處理錯誤
} else {
arr = tmp; // 成功則更新指標
}


上一篇
指標(pointer)與動態記憶體(malloc/calloc/realloc/free)攻略-3
系列文
用leetcode系統化學習C語言12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言